import 'package:flutter/foundation.dart';
import '../permission_model.dart';
import '../role_view_model.dart';
import 'permission_group_model.dart';

class RolePermissionsViewModel extends ChangeNotifier {
  final RoleViewModel _roleViewModel;
  List<Permission> _allPermissions = [];
  List<Permission> _rolePermissions = [];
  bool _isLoading = false;
  String? _error;

  RolePermissionsViewModel(this._roleViewModel);

  List<PermissionGroup> get permissionGroups {
    final Map<int, List<PermissionItem>> groups = {};
    
    // 调试日志
    debugPrint('All Permissions: ${_allPermissions.length}');
    debugPrint('Role Permissions: ${_rolePermissions.length}');
    
    // 获取所有根级菜单
    final List<Permission> rootMenus = _allPermissions
        .where((p) => p.parentId == null || p.parentId == 0)
        .toList();
    
    debugPrint('Root Menus: ${rootMenus.length}');

    // 为每个权限创建分组
    for (var permission in _allPermissions) {
      if (permission.parentId == null || permission.parentId == 0) {
        // 如果是根级权限，创建新分组
        groups[permission.id] = [];
      } else {
        // 将权限添加到对应的父级分组中
        final parentId = permission.parentId ?? 0;
        if (!groups.containsKey(parentId)) {
          groups[parentId] = [];
        }
        groups[parentId]?.add(PermissionItem.fromPermission(
          permission.copyWith(
            isSelected: _rolePermissions.any((rp) => rp.id == permission.id),
          ),
        ));
      }
    }

    return rootMenus.map((menu) {
      // 创建根级权限的PermissionItem
      final rootPermission = PermissionItem.fromPermission(
        menu.copyWith(
          isSelected: _rolePermissions.any((rp) => rp.id == menu.id),
        ),
      );

      return PermissionGroup(
        name: menu.name,
        id: menu.id,
        code: menu.code,
        remark: menu.remark,
        rootPermission: rootPermission,
        permissions: groups[menu.id] ?? [],
        isExpanded: true,
      );
    }).toList();
  }

  bool get isLoading => _isLoading;
  String? get error => _error;

  Future<void> loadPermissions(int roleId) async {
    try {
      _isLoading = true;
      _error = null;
      notifyListeners();

      debugPrint('Loading permissions for role: $roleId');

      final futures = await Future.wait([
        _roleViewModel.getAllPermissions(),
        _roleViewModel.getRolePermissions(roleId),
      ]);

      _allPermissions = futures[0];
      _rolePermissions = futures[1];
      
      debugPrint('Loaded permissions:');
      debugPrint('All permissions count: ${_allPermissions.length}');
      debugPrint('Role permissions count: ${_rolePermissions.length}');
      
      _isLoading = false;
      notifyListeners();
    } catch (e) {
      debugPrint('Error loading permissions: $e');
      _error = '加载权限数据失败：${e.toString()}';
      _isLoading = false;
      notifyListeners();
    }
  }

  void updatePermission(int permissionId, bool value, {bool isRootPermission = false}) {
    if (value) {
      if (!_rolePermissions.any((p) => p.id == permissionId)) {
        final permission = _allPermissions.firstWhere((p) => p.id == permissionId);
        _rolePermissions.add(permission.copyWith(isSelected: true));
        
        // 如果是根权限被选中，自动选中所有子权限
        if (isRootPermission) {
          final childPermissions = _allPermissions
              .where((p) => p.parentId == permissionId)
              .where((p) => !_rolePermissions.any((rp) => rp.id == p.id));
          
          _rolePermissions.addAll(
            childPermissions.map((p) => p.copyWith(isSelected: true))
          );
        }
      }
    } else {
      _rolePermissions.removeWhere((p) => p.id == permissionId);
      
      // 如果是根权限被取消，自动取消所有子权限
      if (isRootPermission) {
        _rolePermissions.removeWhere((p) => 
          _allPermissions.any((ap) => 
            ap.id == p.id && ap.parentId == permissionId
          )
        );
      }
    }
    notifyListeners();
  }

  Future<bool> savePermissions(int roleId) async {
    try {
      _isLoading = true;
      _error = null;
      notifyListeners();

      final selectedPermissionIds = _rolePermissions.map((p) => p.id).toList();
      await _roleViewModel.assignPermissions(roleId, selectedPermissionIds);
      
      _isLoading = false;
      notifyListeners();
      return true;
    } catch (e) {
      _error = e.toString();
      _isLoading = false;
      notifyListeners();
      return false;
    }
  }
}